package com.byd.utils;

import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public final class AESUtils {
	private static final String VIPARA = "0102030405060708";

	public static byte[] encrypt(String content, String seed) throws Exception {
		return encrypt(content.getBytes(), seed.getBytes());
	}

	public static byte[] encrypt(byte[] data, String seed) throws Exception {
		return encrypt(data, seed.getBytes());
	}

	public static byte[] encrypt(String content, byte[] seed) throws Exception {
		return encrypt(content.getBytes(), seed);
	}

	public static byte[] encrypt(byte[] data, byte[] seed) throws Exception {
		final Cipher cipher = getEnCipher(seed);
		return cipher.doFinal(data);
	}

	public static byte[] decrypt(byte[] data, String seed) throws Exception {
		return decrypt(data, seed.getBytes());
	}

	public static byte[] decrypt(byte[] data, byte[] seed) throws Exception {
		final Cipher cipher = getDeCipher(seed);
		return cipher.doFinal(data);
	}

	public static Cipher getEnCipher(String seed) throws Exception {
		return getEnCipher(seed.getBytes());
	}

	public static Cipher getEnCipher(byte[] seed) throws Exception {
		return getCipher(seed, Cipher.ENCRYPT_MODE);
	}

	public static Cipher getDeCipher(String seed) throws Exception {
		return getDeCipher(seed.getBytes());
	}

	public static Cipher getDeCipher(byte[] seed) throws Exception {
		return getCipher(seed, Cipher.DECRYPT_MODE);
	}

	private static Cipher getCipher(byte[] seed, int mode) throws Exception {
		final byte[] seed16 = new byte[16];
		for (int i = Math.min(seed.length, 16) - 1; i >= 0; i--) {
			seed16[i] = seed[i];
		}
		final Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
		final IvParameterSpec parameter = new IvParameterSpec(VIPARA.getBytes());
		final SecretKeySpec keySpec = new SecretKeySpec(seed16, "AES");
		cipher.init(mode, keySpec, parameter);
		return cipher;
	}

	public static Cipher getAndroidCipher(byte[] seed, int mode) throws Exception {
		final KeyGenerator kgen = KeyGenerator.getInstance("AES");
		final SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "Crypto");
		random.setSeed(seed);
		kgen.init(128, random);
		final SecretKey secretKey = kgen.generateKey();
		final SecretKeySpec key = new SecretKeySpec(secretKey.getEncoded(), "AES");
		final Cipher cipher = Cipher.getInstance("AES");
		cipher.init(mode, key);
		return cipher;
	}
}
